package cn.stacey.jd.web;





import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.stacey.jd.domain.Product;
import cn.stacey.jd.service.ProductService;


@Controller
public class ProductController {
	@Autowired
	ProductService service;
	
	@RequestMapping("home.action")
	public String home() {
		
		return "redirect:search.action?keyword=&category=&price=";
	}
	//String keyword,String category,String price,
	//Pageable pageable 
	@RequestMapping("/search")
	public String search(
			@RequestParam("keyword") String keyword,
			@RequestParam("category") String category,
			@RequestParam("price") String price,
			@RequestParam(name="page", defaultValue = "0") Integer page,
			@RequestParam(name="size", defaultValue = "10") Integer size,
			@RequestParam(name = "sort", defaultValue = "0") Integer s,
			Model model
			
			) {
		//判断传来的价格Integer类型为0(表示升序)还是1（表示降序）
		//service接收的样式为  Sort.by("price").ascending()
		Sort sort = Sort.by("price");
		sort=(s==0)?sort.ascending():sort.descending();
		
		PageRequest pageable = PageRequest.of(page, size, sort);
		Page<Product> pageData = service.search(keyword, category, price, pageable);
		model.addAttribute("pageData", pageData);
//		pageData.getTotalElements();
//		pageData.getNumber();
//		pageData.getSize();
		//参数回显
		if(!StringUtils.isEmpty(keyword)) {
			model.addAttribute("keyword",keyword);
		}
		if(!StringUtils.isEmpty(category)) {
			model.addAttribute("category",category);
		}
		if(!StringUtils.isEmpty(price)) {
			model.addAttribute("price",price);
		}
		//pageData中已经回显了
//		if(!StringUtils.isEmpty(page)) {
//			model.addAttribute("page",page);
//		}
//		if(!StringUtils.isEmpty(size)) {
//			model.addAttribute("size",size);
//		}
		if(!StringUtils.isEmpty(sort)) {
			model.addAttribute("sort",s);
		}
		return "product_list";
		
	}
}
